﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GettingStarted.Model;
using NUnit.Framework;
using Xtensive.Orm;
using Xtensive.Orm.Configuration;

namespace GettingStarted
{
    internal class Program
    {
        [Test]
        public static void Main()
        {
            // Loading domain configuration section with name "Default" from app.config.
            var domainConfiguration = DomainConfiguration.Load("Default");
            // Building domain (a representation of database)
            var domain = Domain.Build(domainConfiguration);

            // 1. Creating entities

            // Opening new session (connection to database)
            using (var session = domain.OpenSession()) {
                // Opening transaction
                using (var tx = session.OpenTransaction()) {
                    // Creating new Person instance, passing Session to constructor, settings properties
                    var person = new Person(session)
                    {
                        FirstName = "John",
                        LastName = "Smith",
                        BirthDate = new DateTime(1950, 1, 1)
                    };
                    // Marking transaction as completed to persist changes
                    tx.Complete();
                }
            }

            // 2. Fetching entities from database

            using (var session = domain.OpenSession()) {
                using (var tx = session.OpenTransaction()) {

                    // Querying persons from session.Query endpoint
                    var persons = session.Query.All<Person>().ToList();

                    foreach (var person in persons) {
                        Console.WriteLine("{0} {1}, born {2}", person.FirstName, person.LastName, person.BirthDate);
                    }

                    tx.Complete();
                }
            }

            // 3. Removing entities

            using (var session = domain.OpenSession()) {
                using (var tx = session.OpenTransaction()) {

                    // Finding person instance
                    var person = session.Query.All<Person>().First();
                    // Marking it for removal
                    person.Remove();
                    // Marking transaction as complete to persist changes
                    tx.Complete();
                }
            }
        }
    }
}